//应付审核
interface IFeeAuditViewModel extends IBaseViewModel<IFeeAuditQueryTerms>{
    /**
     * ui-grid
     */
    gridOptions:uiGrid.IGridOptionsOf<FinanceFeeListItemResponse>;
    /**
     * 选中费用列表
     */
    selectedFeeListInfo:selectFeeList[];
    /**
     * 付款方式下拉
     */
    paymentMethodDropDown:ValueListItemResponse[];
    /**
     * 费用类型下拉
     */
    feeTypeDropDown:ValueListItemResponse[];
    /**
     * 费用状态
     */
    feeStatusDropDown:ValueListItemResponse[];
    /**
     * 删除已选费用
     */
    feeSelectedDelet(id:string):void;
    /**
     * 全选事件
     */
    selectAllEve():void;
    /**
     * 费用审核
     */
    feeAuditEve():void;

    /**
     * 审核通过
     */
    feeAuditPass():void;

    /**
     * 退回办理
     */
    feeBackTransact():void;
    /**
     * 费用审核-通过-退回按钮
     */
    feeAuditDisBtn:boolean;
    /**
     * 导出
     */
    exportFeeList():void;
    /**
     * 导出btn
     */
    exportFeeBtn
    /**
     * 人工审核按钮
     */
    auditChange():void;

    /**
     * 是否是自动审核btn
     */
    auditBtn:string;
    /**
     * 是否是自动审核name
     */
    auditName:string;
    /**
     * 单笔限额
     */
    feeQuota:string;
    /**
     * 单笔运单限额
     */
    carrierOrderQuota:string;
    /**
     * 查询
     */
    query():void;
    /**
     * 列表高度
     */
    heightA:number;

}
/**
 * 查询条件
 */
interface IFeeAuditQueryTerms{
    /**
     * 合同号
     */
    contractNumber:string;
    /**
     * 承运商
     */
    carrierName:string;
    /**
     * 付款方式
     */
    paymentMethod:string;
    /**
     * 申领人
     */
    applicant:string
    /**
     * 申请起始时间
     */
    startTime:string;
    /**
     * 申请结束时间
     */
    endTime:string;
    /**
     * 车牌号
     */
    carCode:string;
    /**
     * 费用类型
     */
    feeType:string;
    /**
     * 费用状态
     */
    feeStatuslist:string;
    /**
     * 发货地址
     */
    origin:string;
    /**
     * 目的地址
     */
    destination:string;
}

/**
 * 选中的费用列表
 */
interface selectFeeList{
    /**
     * 费用id
     */
    id:string;
    /**
     * 费用状态
     */
    feeStatus:string;
    /**
     * 费用可识别编号
     */
    feeCode:string;
}


class feeAuditController extends ListController<IFeeAuditViewModel,IFeeAuditQueryTerms>{
    gridApi: uiGrid.IGridApiOf<FinanceFeeListItemResponse>;
    /**
     * 选定选中，防止在翻页恢复选中效果时候误操作
     */
    lockSelect: boolean = false;
    orderBy: number = 0;
    asc: boolean = true;

    constructor($scope:IFeeAuditViewModel,private feeService:IFeeService,private $ngBootbox:BootboxService,private orderService:IorderService,private $state:ng.ui.IStateService,private routeService:routeService,private logisticsService:ILogisticsService,private valueService:IValueService,private authorizationService:IAuthorizationService,private $timeout:ng.ITimeoutService,private $location:ng.ILocationService,private exportService:IexportService){
         super($scope);
         this.init();
    }

    init():void{
        super.init();
        this.$scope.queryTerms = {
            contractNumber:"",
            carrierName:"",
            paymentMethod:"",
            applicant:"",
            startTime:"",
            endTime:"",
            carCode:"",
            feeType:"",
            feeStatuslist:"1",
            origin:"",
            destination:""
        }
        this.$scope.selectedFeeListInfo = [];
        this.$scope.gridOptions = {
			enableRowSelection: true,
			enableRowHeaderSelection: false,
			enableSelectAll: false,//全选禁用
			paginationPageSizes: [10, 20, 30],
			useExternalPagination: true,
			useExternalSorting: true,
			enableColumnResizing: true,
            multiSelect:true,
            columnDefs: [
                { displayName: "费用编号", field: 'feeCode', enableColumnMenu: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.feeCode}}</div>', width: '8%' },
                { displayName: "合同号", field: 'contractNumber', enableColumnMenu: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.contractNumber}}</div>',width:'6%' },
                { displayName: "发货地址", field: 'startAddress', enableColumnMenu: false,  cellTemplate: '<div ng-repeat="item in row.entity.orderList" class="LTL-list" >{{item.startAddress}}</div>',width:'12%' },
                { displayName: '送货地址', field: 'endAddress', enableColumnMenu: false,  cellTemplate: '<div ng-repeat="item in row.entity.orderList" class="LTL-list" >{{item.endAddress}}</div>',width:'12%' },
                { displayName: '合同状态', field: 'contractStatus', enableColumnMenu: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.contractStatus}}</div>' },
                { displayName: '承运商', field: 'carrier', enableColumnMenu: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.carrier}}</div>' },
                { displayName: '车牌号', field: 'carCode', enableColumnMenu: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.carCode}}</div>' },
                { displayName: '付款方式', field: 'paymentMethod', enableColumnMenu: false, enableSorting: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.paymentMethod}}</div>' },
                { displayName: '费用类型', field: 'feeType', enableColumnMenu: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.feeType}}</div>' },
                { displayName: '费用金额', field: 'feeAmount', enableColumnMenu: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.feeAmount}}</div>' },
                { displayName: '费用状态', field: 'feeStatus', enableColumnMenu: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.feeStatus}}</div>' },
                { displayName: '申领人员', field: 'applicant', enableColumnMenu: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.applicant}}</div>' },
                { displayName: '申请日期', field: 'creationTime', enableColumnMenu: false,enableSorting: false, cellTemplate: '<div style="height:{{39 * row.entity.orderList.length}}px;"class="single-list">{{row.entity.creationTime}}</div>', width: '7%' }
            ],
            onRegisterApi: (gridApi) => {
                this.gridApi = gridApi;
                //存储翻页
                // gridApi.pagination.on.paginationChanged(this.$scope,(skipSize,pageSize)=>{
                //     this.paginationChanged(skipSize,pageSize,this.$state);
                // });
                //不存储翻页
                gridApi.pagination.on.paginationChanged(this.$scope, this.paginationChanged);
                gridApi.core.notifyDataChange("options");
                gridApi.core.on.sortChanged(this.$scope, this.sortChange);
                gridApi.selection.on.rowSelectionChanged(this.$scope, this.selectChange);
            }   
        };

        this.$scope.feeAuditDisBtn = false;
        this.$scope.exportFeeBtn = false;
        this.$scope.auditBtn = "自动审核";
        this.$scope.auditName = "人工审核";

        
        this.query();
        this.loadDropDown();
        this.$scope.selectAllEve = ()=>{
            this.selectAllEve(this.$scope.gridOptions.data)
        }
        this.$scope.feeAuditEve = this.feeAuditEve;
        this.$scope.feeAuditPass = this.feeAuditPass;
        this.$scope.feeBackTransact = this.feeBackTransact
        this.$scope.auditChange = this.auditChange;
        this.$scope.feeSelectedDelet = (id)=>{
            this.feeSelectedDelet(id,this.$scope.gridOptions.data)
        };
        this.getAuditInfo();
        this.getAuthority();

        $("#opendataTime").click(()=>{
             $('#startTime').datetimepicker('show');
        });
        $("#opendataTimeEnd").click(()=>{
             $('#endTime').datetimepicker('show');
        });
    }


    loadData(queryTerms:IFeeAuditQueryTerms,skip:number,count:number):void{
        if(this.$scope.queryTerms.feeStatuslist == "" || !this.$scope.queryTerms.feeStatuslist){this.$scope.queryTerms.feeStatuslist = "0,1,2,3,4,5,6,7,8,9,10,11";}
        let feeStatuslist = this.$scope.queryTerms.feeStatuslist
        if(this.$scope.queryTerms.feeStatuslist == "10"){ feeStatuslist = "10,11";}
        this.feeService.getFinanceFeeList(this.orderBy.toString(),this.asc,"","","","",queryTerms.applicant,queryTerms.contractNumber,"","",queryTerms.startTime,queryTerms.endTime,"","","","","","","","",queryTerms.carrierName,"",queryTerms.carCode,queryTerms.feeType,feeStatuslist,queryTerms.origin,queryTerms.destination,queryTerms.paymentMethod,"",skip,count).then(result=>{
            // this.$scope.gridOptions.totalItems = result.data.extData;
            this.$scope.gridOptions.data = result.data.data;
             this.resumeSelectedItem(this.$scope.gridOptions.data);
            let gridHArr = 0;
            result.data.data.forEach((item,index) => { gridHArr =  gridHArr + item.orderList.length; });
            this.$scope.heightA = (gridHArr*39)+96;
            if(skip==0){ this.$scope.gridOptions.paginationCurrentPage = 1; };
            this.$scope.querying = false;
        },error=>{this.$scope.querying = false});
    }

    getListCount():void{
        if(this.$scope.queryTerms.feeStatuslist == "" || !this.$scope.queryTerms.feeStatuslist){this.$scope.queryTerms.feeStatuslist = "0,1,2,3,4,5,6,7,8,9,10,11";}
        let feeStatuslist = this.$scope.queryTerms.feeStatuslist
        if(this.$scope.queryTerms.feeStatuslist == "10"){ feeStatuslist = "10,11";}

        this.feeService.getFinanceFeeCount("","","","",this.$scope.queryTerms.applicant,this.$scope.queryTerms.contractNumber,"","",this.$scope.queryTerms.startTime,this.$scope.queryTerms.endTime,"","","","","","","","",this.$scope.queryTerms.carrierName,"",this.$scope.queryTerms.carCode,        this.$scope.queryTerms.feeType,feeStatuslist,this.$scope.queryTerms.origin,this.$scope.queryTerms.destination,this.$scope.queryTerms.paymentMethod,"").then(res=>{
            this.$scope.gridOptions.totalItems = res.data.extData;
        })
    }

    localHistory():void{
        super.localHistory(this.$state)
    }
    getHistory():void{
        super.getHistory(this.$state,this.$location)
    }

    /**
     * 排序事件触发
     */
    sortChange=(grid: uiGrid.IGridInstanceOf<FinanceFeeListItemResponse>, sortColumns: Array<uiGrid.IGridColumnOf<FinanceFeeListItemResponse>>)=> {
        if (sortColumns.length == 0) {
           this.reload();
        } else {
            let sortItem = sortColumns[0];
            switch (sortItem.name) {
                case "feeCode": {
                    this.orderBy = 1;
                } break;
                case "startAddress": {
                    this.orderBy = 6;
                } break;
                case "endAddress": {
                    this.orderBy = 7;
                } break;
                case "contractStatus": {
                    this.orderBy = 12;
                } break;
                case "carrier": {
                    this.orderBy = 14;
                } break;
                case "carCode": {
                    this.orderBy = 11;
                } break;
                case "feeType": {
                    this.orderBy = 19;
                } break;
                case "feeAmount": {
                    this.orderBy = 15;
                } break;
                case "feeStatus": {
                    this.orderBy = 13;
                } break;
                case "applicant":{
                    this.orderBy = 18;
                }break;
                case "ReceiptStatus": {
                    this.orderBy = 9;
                } break;
            }
            this.asc = sortItem.sort.direction == "asc";
            this.reload();
        }
    }

    /**
     * 选择事件
     */
    selectChange=(row:uiGrid.IGridRowOf<FinanceFeeListItemResponse>)=>{
        if(this.lockSelect){return;};
        if(row.isSelected){
            this.$scope.selectedFeeListInfo.push({
                id:row.entity.id,
                feeStatus:row.entity.feeStatus,
                feeCode:row.entity.feeCode
            });
        }else{
            this.$scope.selectedFeeListInfo.forEach((item,index)=>{
                if(row.entity.id == item.id){
                    this.$scope.selectedFeeListInfo.splice(index,1);
                }
            });
        }
    }

    /**
     * 删除选中费用
     */
    feeSelectedDelet=(arg:string,data:string | FinanceFeeListItemResponse[])=>{
        this.$scope.selectedFeeListInfo.forEach((item,index)=>{
            if(arg === item.id){
                this.$scope.selectedFeeListInfo.splice(index,1);
                if(this.isfeeListResponse(data)){
                    data.forEach((items,indexs)=>{
                        if(item.id == items.id){
                            if(this.isfeeListResponse(data)){
                                this.gridApi.selection.unSelectRow(data[indexs]);
                            }
                        }
                    });
                }
            }
        });
    }
    
    //断言
    isfeeListResponse(response: string | FinanceFeeListItemResponse[]): response is FinanceFeeListItemResponse[] {
        return (<FinanceFeeListItemResponse[]>response).forEach !== undefined;
    }

    /**
     * 全选
     */
    selectAllEve=(data: string | FinanceFeeListItemResponse[])=>{
        if(this.isfeeListResponse(data)){
            data.forEach((item,index)=>{
                if(item.feeStatus ==="办理"){
                    if(this.isfeeListResponse(data)){
                        this.gridApi.selection.selectRow(data[index]);
                    }
                }
            })
        }
    }


    /**
     * 翻页后选中
     */
    resumeSelectedItem(data: string | FinanceFeeListItemResponse[]):void{
        if(this.$scope.selectedFeeListInfo.length <1){return};
        if(this.isfeeListResponse(data)){
            data.forEach((item,index)=>{
                this.$scope.selectedFeeListInfo.forEach((itemS,indexS)=>{
                    if(item.id === itemS.id){
                        this.$timeout(()=>{
                            if(this.isfeeListResponse(data)){
                                this.lockSelect = true;
                                this.gridApi.selection.selectRow(data[index]);
                                this.lockSelect = false;
                            }
                        })
                    }
                })
            })
        }
    }

    /**
     * 费用审核
     */
    feeAuditEve=()=>{
        let sFeeList = this.$scope.selectedFeeListInfo;
        if(sFeeList.length<1){ this.$ngBootbox.alert("请选择需审核的费用");return;}else if(sFeeList.length > 1){
            this.$ngBootbox.alert("只能选择一条费用");
            return;
        }
        this.feeService.feeDetail(sFeeList[0].id).then(res=>{
            let carrierOrderId = res.data.carrierOrderId;
            this.orderService.carryOrder(carrierOrderId).then(res=>{
                let data = res.data;
                if (data.orderList.length > 1) {
                    this.$state.go("app.fee.feeBreakbulkDetail", { feeId: sFeeList[0].id, carrierOrderId: carrierOrderId, pageName: 'Audit',feeStatus:sFeeList[0].feeStatus })
                } else {
                    this.$state.go("app.fee.feeOrderDetailController", { feeId: sFeeList[0].id, orderId: data.orderList[0], carrierOrderId:carrierOrderId, name: 'Audit' })
                }   
            })
        })
    }
    /**
     * 审核通过
     */
    feeAuditPass=()=>{
        let sFeeList = this.$scope.selectedFeeListInfo;
        let isAuditPass = true;
        let feeIdList = [];
        if(sFeeList.length < 1){this.$ngBootbox.alert("请选择需审核的费用");return;};
        sFeeList.forEach((item,index)=>{
            if(item.feeStatus != "办理"){
                isAuditPass = false;
                this.$ngBootbox.alert("请选择办理状态的费用");
                feeIdList.length = 0;
                return false;
            }else{
                feeIdList.push(item.id);
            }
        });

        if(isAuditPass){
            this.$ngBootbox.confirm("确定审核通过吗?").then(()=>{
                this.feeService.auditedFee(feeIdList.join(",")).then((res)=>{
                    feeIdList.length = 0;
                    if(!this.queryTerms.feeStatuslist){
                         this.queryTerms.feeStatuslist = "1,2,3,4,5,6,7,8,9,10,11"
                    }
                    this.$scope.selectedFeeListInfo.length = 0;
                   
                    this.query();
                })
            },()=>{return});
        }

    }
    /**
     * 退回办理
     */
    feeBackTransact=()=>{
        let sFeeList = this.$scope.selectedFeeListInfo;
        let feeIdList = [];
        let isAuditPass = true;
        if(sFeeList.length<1){ this.$ngBootbox.alert("请选择需审核的费用"); return;}else if(sFeeList.length > 1){
            this.$ngBootbox.alert("只能选择一条费用");
            return;
        }
        sFeeList.forEach((item,index)=>{
            if(item.feeStatus != "办理"){
                isAuditPass = false;
                this.$ngBootbox.alert("请选择办理状态的费用");
                feeIdList.length = 0;
                return false;
            }else{
                feeIdList.push(item.id);
            }
        });

        if(isAuditPass){
            this.$ngBootbox.confirm("确定退回办理吗?").then(()=>{
                this.feeService.returnManage(feeIdList.join(",")).then((res)=>{
                    feeIdList.length = 0;
                    if(!this.queryTerms.feeStatuslist){
                         this.queryTerms.feeStatuslist = "1,2,3,4,5,6,7,8,9,10,11"
                    }
                    this.$scope.selectedFeeListInfo.length = 0;
                    this.query();
                })
            },()=>{return});
        }
    }

    /**
     * 导出
     */
    exportFunc=()=>{
        if(this.$scope.gridOptions.totalItems>60000){
            this.$ngBootbox.alert('导出数据不可超过6万条');
            return;
        }else{
            if(this.$scope.queryTerms.feeStatuslist == "" || !this.$scope.queryTerms.feeStatuslist){this.$scope.queryTerms.feeStatuslist = "0,1,2,3,4,5,6,7,8,9,10,11";}
            let feeStatuslist = this.$scope.queryTerms.feeStatuslist;
            if(this.$scope.queryTerms.feeStatuslist == "10"){ feeStatuslist = "10,11";}
           this.exportService.export(this.orderBy,this.asc,"","","","",this.queryTerms.applicant,this.queryTerms.contractNumber,"","",this.queryTerms.startTime,this.queryTerms.endTime,
           "","","","","","","","",this.queryTerms.carrierName,"",this.queryTerms.carCode,this.queryTerms.feeType,feeStatuslist,this.queryTerms.origin,this.queryTerms.destination,this.queryTerms.paymentMethod)
        }
        
    }
    /**
     * 切换审核按钮
     */
    auditChange=()=>{ 
        var self = this;
        this.logisticsService.changeIsAutoAuditFee().then(function (res) {
            res.data.isAutoAuditFee ? self.$scope.auditBtn = "人工审核" : self.$scope.auditBtn = "自动审核";
            res.data.isAutoAuditFee ? self.$scope.auditName = "自动审核" : self.$scope.auditName = "人工审核";
        });
    }
 
    /**
     * 获取是否自动审核信息
     */
    getAuditInfo():void{
        this.logisticsService.getAutoAuditDetail().then(res=>{
            res.data.isAutoAuditFee ? this.$scope.auditBtn = "人工审核" : this.$scope.auditBtn = "自动审核";
            res.data.isAutoAuditFee ? this.$scope.auditName = "自动审核" : this.$scope.auditName = "人工审核";
            this.$scope.feeQuota = res.data.feeQuota;//单笔限额
		    this.$scope.carrierOrderQuota = res.data.carrierOrderQuota;//运单限额
        })
    }
    /**
     * 获取按钮权限
     */
    getAuthority():void{
        this.authorizationService.auth("24E0A026891BC3906D2ECCD7DF5ABC95396B751BD74B62C7").then(res=>{
            this.$scope.feeAuditDisBtn = res.data.extData;
        });
        this.authorizationService.auth("24E0A026891BC3903C7917417F680C9D095BBECCE3ACDC9D").then(res=>{
            this.$scope.exportFeeBtn = res.data.extData;
        });
    }
    /**
     * 加载枚举
     */
    loadDropDown():void{
        this.$scope.feeStatusDropDown = this.valueService.getFeeStatusList().data;
        this.$scope.feeTypeDropDown = this.valueService.getFeeTypeList().data;
        this.$scope.paymentMethodDropDown = this.valueService.getPaymentMethodList().data;
    }
}   
angular.module("tms").controller("feeAuditController",["$scope","feeService","$ngBootbox","orderService","$state","routeService","logisticsService","valueService","authorizationService","$timeout","$location","exportService",feeAuditController])